package com.interview.rtc.aigc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.interview.rtc.aigc.mapper.UserMapper;
import com.interview.rtc.aigc.dao.UserDao;
import com.interview.rtc.aigc.service.UserService;
import com.interview.rtc.aigc.common.ErrorCode;
import com.interview.rtc.aigc.utils.ExceptionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public UserDao register(UserDao user) {
        // 检查用户名是否已存在
        QueryWrapper<UserDao> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        UserDao existUser = userMapper.selectOne(queryWrapper);
        
        // 使用断言工具简化异常处理
        ExceptionUtil.assertFalse(existUser != null, ErrorCode.USER_ALREADY_EXIST, "用户名已存在");

        // 密码加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(encryptedPassword);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        // 保存用户
        userMapper.insert(user);
        
        // 清除密码后返回
        user.setPassword(null);
        return user;
    }

    @Override
    public UserDao login(String username, String password) {
        // 查询用户
        QueryWrapper<UserDao> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UserDao user = userMapper.selectOne(queryWrapper);
        
        // 检查用户是否存在，不存在则抛出异常
        ExceptionUtil.assertNotNull(user, ErrorCode.USER_NOT_EXIST, "用户不存在");
        
        // 验证密码
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        ExceptionUtil.assertTrue(
            user.getPassword().equals(encryptedPassword), 
            ErrorCode.USER_PASSWORD_ERROR, 
            "密码错误"
        );
        
        // 清除密码后返回
        user.setPassword(null);
        return user;
    }

    @Override
    @Transactional
    public UserDao updateUser(UserDao user) {
        // 首先检查用户是否存在
        UserDao existingUser = userMapper.selectById(user.getId());
        ExceptionUtil.assertNotNull(existingUser, ErrorCode.USER_NOT_EXIST, "用户不存在");
        
        user.setUpdateTime(new Date());
        userMapper.updateById(user);
        
        // 获取更新后的用户数据
        UserDao updatedUser = userMapper.selectById(user.getId());
        updatedUser.setPassword(null);
        return updatedUser;
    }

    @Override
    public UserDao getUserById(Long userId) {
        UserDao user = userMapper.selectById(userId);
        ExceptionUtil.assertNotNull(user, ErrorCode.USER_NOT_EXIST, "用户不存在");
        
        if (user != null) {
            // 返回前清除密码
            user.setPassword(null);
        }
        return user;
    }

    @Override
    public List<UserDao> getAllUsers() {
        List<UserDao> users = userMapper.selectList(null);
        // 清除所有用户的密码
        users.forEach(user -> user.setPassword(null));
        return users;
    }
}
